<!doctype html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>瀑布流2</title>
		<style type="text/css">
			body{
				margin: 0px;
			}
			.box{
				width: 100%;
				height: 1000px;
				border: 1px red solid;
				margin: 0 auto;
				position: relative;
			}
			.item{
				position: absolute;
				width: 200px;
				background-color: pink;

				font-size: 50px;
				text-align: center;
				color: white;
			}
		</style>
	</head>
	<body>
		<div class="box">
			
		</div>
	</body>
	<script type="text/javascript">
		var box = document.getElementsByClassName('box')[0];
		

		var firstN = parseInt((window.innerWidth+12) / 210);//代表几列
		box.style.width = firstN * 210 - 10 + "px";
		var allHeight = [];//每列总高度
		for(var i = 0; i < firstN; i++){
			allHeight[i] = 0;
		}

		for(var j = 0; j < 20; j++){
			// 1、生成div
			var newDiv = document.createElement("div");
			// 2、设置样式
			newDiv.className = "item";
			newDiv.style.height = parseInt(Math.random()*100 + 50) + "px";
			box.appendChild(newDiv);
			// 3、找总高度最小列的下标
			var minIndex = 0;
			for(var i = 1; i < firstN; i++){
				if (allHeight[minIndex] > allHeight[i]) {
					minIndex = i;
				}
			}
			// 4、根据下标设置left top
			newDiv.style.left = minIndex * (newDiv.offsetWidth + 10) + "px";
			newDiv.style.top = allHeight[minIndex] + "px";
			// 5、div放入最短列之后，最短列总高度增加；
			newDiv.innerHTML = j + 1;
			allHeight[minIndex] += (newDiv.offsetHeight + 10);
		}

		
		window.onresize = function(){
			var n = parseInt((window.innerWidth+12) / 210);//代表几列
			if (n == firstN) {
				return;
			}
			firstN = n;
			box.style.width = n * 210 - 10 + "px";
			var allHeight = [];//每列总高度
			for(var i = 0; i < n; i++){
				allHeight[i] = 0;
			}
			var divS = document.getElementsByClassName("item");
			for(var j = 0; j < divS.length; j++){
				// 1、生成div
				var newDiv = divS[j];
				// 3、找总高度最小列的下标
				var minIndex = 0;
				for(var i = 1; i < n; i++){
					if (allHeight[minIndex] > allHeight[i]) {
						minIndex = i;
					}
				}
				// 4、根据下标设置left top
				newDiv.style.left = minIndex * (newDiv.offsetWidth + 10) + "px";
				newDiv.style.top = allHeight[minIndex] + "px";
				// 5、div放入最短列之后，最短列总高度增加；
				newDiv.innerHTML = j + 1;
				allHeight[minIndex] += (newDiv.offsetHeight + 10);
			}
		}






	</script>
</html>